package com.marcinklos.filipides.web;

import java.security.Principal;
import java.util.EnumSet;

import javax.jdo.PersistenceManager;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import com.marcinklos.filipides.User;
import com.marcinklos.filipides.UserRole;

@Controller
public class FilipidesController {
	@RequestMapping("/summary")
    public ModelAndView displayPrivate() {
        String message = "Secret message.";
        return new ModelAndView("summary", "message", message);
    } 
	
	@RequestMapping(value="/register", method=RequestMethod.GET)
    public ModelAndView displayRegistrationForm() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User)authentication.getPrincipal();
        return new ModelAndView("register", "user", user);
    } 
	
	@RequestMapping(value="/register", method=RequestMethod.POST)
    public ModelAndView processRegistrationForm(
    		@RequestParam("firstName") String firstName, 
    		@RequestParam("lastName") String lastName, 
    		@RequestParam("email") String email, 
    		Principal authentication) {
		Authentication auth = (Authentication) authentication;
		User user = (User)auth.getPrincipal();
        user.setRoles(EnumSet.of(UserRole.ROLE_USER));
        PersistenceManager pm = PMF.get().getPersistenceManager();
        pm.makePersistent(user);
        pm.close();
        return new ModelAndView("account", "user", user);
    }
	
	@RequestMapping("/account")
    public ModelAndView displayAccountInfo() {
        String message = "Secret message.";
        return new ModelAndView("account", "message", message);
    } 

	@RequestMapping("/signout")
    public String signOut() {
        return "redirect:/";
    } 
	
	@RequestMapping("/index")
    public ModelAndView welcome() {
        return new ModelAndView("welcome");
    } 
}
